package cn.zc.security.service;

import cn.hutool.core.lang.UUID;
import cn.zc.common.core.constants.CacheConstants;
import cn.zc.common.core.constants.JwtConstants;
import cn.zc.redis.service.RedisService;
import cn.zc.common.core.domain.LoginUser;
import cn.zc.common.core.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
public class TokenService {
    @Autowired
    private RedisService redisService;
    public  String createToken(String userId, String secret,int identity) {
        Map<String, Object> hashMap = new HashMap<>();
        String userKey = UUID.fastUUID().toString();
        hashMap.put(JwtConstants.LOGIN_USER_ID,userId);
        hashMap.put(JwtConstants.LOGIN_USER_Key, userKey);
        String token = JwtUtils.createToken(hashMap, secret);
        String key = CacheConstants.LOGIN_TOKEN_KEY + userKey;
        LoginUser loginUser = new LoginUser();
        //1为普通用户，2为管理员
        loginUser.setIdentity(identity);
        redisService.setCacheObject(key, loginUser, CacheConstants.EXP, TimeUnit.MINUTES);
        return token;
    }
    //延长token有效时间
    public void refreshToken(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息 解析payload中信息
            if (claims == null) {
                //由于在过滤器中已经做了判断这里不做处理，如果出错仅作日志记录
                log.error("拦截器中解析token失败，claims为空");
                return;
            }
        }
        catch (Exception e) {
            //由于在过滤器中已经做了判断这里不做处理，如果出错仅作日志记录
            log.error("拦截器中解析token失败", e);
            return;
        }
        String userKey = JwtUtils.getUserKey(claims);
        String key = CacheConstants.LOGIN_TOKEN_KEY + userKey;
        //获得剩余有效时间
        Long expire = redisService.getExpire(key, TimeUnit.MINUTES);
        //刷新token有效时间
        if(expire!=null&&expire<CacheConstants.REFRESH_TIME){
            redisService.expire(key, CacheConstants.EXP, TimeUnit.MINUTES);
        }
    }
}
